package concept.misc;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Car implements Serializable
{
	private static final long serialVersionUID = 1L;
	int doors = 5;
	static int wheels = 4;
	transient int windscreen = 1;
	
	public String toString()
	{
		return ""+doors+wheels+windscreen;
	}
}

class Movie implements Externalizable{

    private String name;
    private long releaseYear;
    private String language;

    public Movie(){		
    }

    public Movie(String name, long releaseYear, String language){
        this.name = name;
        this.releaseYear = releaseYear;
        this.language = language; 
    }

    public String toString(){
        return name + " , " + releaseYear + " , " + language;
    }

    @Override
    public void readExternal(ObjectInput in) 
    throws IOException,ClassNotFoundException {

        name = in.readUTF();
        releaseYear = in.readLong();
        language = in.readUTF();
    }

    @Override
    public void writeExternal(ObjectOutput out) 
    throws IOException {
        out.writeUTF(name);
        out.writeLong(releaseYear);
        out.writeUTF(language);
    }
}


public class SerializationLab
{
	public static void main(String[] args) throws Exception
	{
		doCar();
		doMovie();
	}
	
	static void doCar()
	{
		Car car = new Car();
		Car.wheels = 44;
		
		System.out.println("Car before serialized: "+car);
		
		FileOutputStream fos;
		FileInputStream fis;
		
		try
		{
			fos = new FileOutputStream("C:/temp/car.ser");
			fis = new FileInputStream("C:/temp/car.ser");
			
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(car);
			oos.close();
			
			ObjectInputStream ois = new ObjectInputStream(fis);
			Car car2 = (Car)ois.readObject();
			ois.close();
			
			System.out.println("Car after deserialized: "+car2);
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	static void doMovie() throws Exception
	{
		Movie harry = new Movie(
                "Harry Potter and the Order of Phoenix", 2007, "English");

            ObjectOutputStream output = new ObjectOutputStream(
                new FileOutputStream("C:/temp/movie.ser"));
            output.writeObject(harry);
            output.close();

            ObjectInputStream input = new ObjectInputStream(
                new FileInputStream("C:/temp/movie.ser"));
            harry = (Movie)input.readObject();
            System.out.println(harry);
            input.close();	
	}
}
